package beanpay

import (
	"gitee.com/micro-plat/fas/modules/const/enum"
	"gitee.com/micro-plat/fas/modules/sdkdb"
	"github.com/asaskevich/govalidator"
	"github.com/micro-plat/beanpay/beanpay"
	"github.com/micro-plat/lib4go/errs"
)

//UpChannelPay 上游扣款
func UpChannelPay(params *UpPay) error {

	// 验证参数
	if b, err := govalidator.ValidateStruct(params); !b {
		return errs.NewErrorf(406, "BPay:UpChannelPay:govalidator.参数验证错误err:%+v,param:%+v", err, params)
	}
	// 获取数据操作对象
	_, trans, err := sdkdb.GetDBTrans(nil)
	if err != nil {
		return err
	}

	// 获取beanpay接口
	if params.UpCostAmount > 0 {
		bp := beanpay.GetAccount(params.Ident, enum.AccountGroups.UpChannel)
		_, err = bp.DeductAmount(trans, params.UpChannelNo, params.TradeDeliveryNo, beanpay.TPTrade, params.UpCostAmount, params.Memo)
		if err != nil {
			trans.Rollback()
			return errs.NewErrorf(errs.GetCode(err), "上游扣款成本，err:%v", err)
		}
	}

	// 佣金扣款
	if params.UpCommissionAmount != 0 {
		_, err := beanpay.GetAccount(params.Ident, enum.AccountGroups.UpCommission).AddAmount(
			trans, params.UpChannelNo, params.TradeDeliveryNo, params.UpCommissionAmount, params.Memo)
		if err != nil {
			trans.Rollback()
			return errs.NewErrorf(errs.GetCode(err), "上游佣金扣款成本，err:%v", err)
		}
	}

	// 服务费扣款
	if params.UpServiceAmount != 0 {
		_, err := beanpay.GetAccount(params.Ident, enum.AccountGroups.UpService).AddAmount(
			trans, params.UpChannelNo, params.TradeDeliveryNo, params.UpServiceAmount, params.Memo)
		if err != nil {
			trans.Rollback()
			return errs.NewErrorf(errs.GetCode(err), "上游服务费扣款成本，err:%v", err)
		}
	}
	trans.Commit()
	return nil
}
